package com.uploadFile.service;

/**
 * @Author pl711@qq.com
 * @PackageName uploadFile
 * @Package com.uploadFile.service
 * @Date 2024/5/11 0:40
 * @Version 1.0
 */
import com.uploadFile.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Set;

@Service
@EnableScheduling
public class FileExpirationService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OssConfig ossConfig;
    public void storeFileWithExpiry(String filePath) {
        // 当前时间加上30分钟作为过期时间
        LocalDateTime expiryTime = LocalDateTime.now().plusMinutes(5);
        long expiryTimestamp = expiryTime.toInstant(ZoneOffset.UTC).toEpochMilli();
        // 存储文件路径和过期时间戳到Redis
        redisTemplate.opsForValue().set(filePath, String.valueOf(expiryTimestamp), Duration.ofMinutes(5));
    }

//    @Scheduled(cron = "0 0/5 * * * ?") // 每30分钟执行一次
    public void cleanupOldFiles() {
        // 获取Redis中所有文件信息（可能需要优化以避免性能问题）
        Set<String> keys = redisTemplate.keys("*");
        if (keys != null) {
            for (String key : keys) {
                String uploadTimeStampString = (String) redisTemplate.opsForValue().get(key);
                if (uploadTimeStampString != null) {
                    long uploadTime = Long.parseLong(uploadTimeStampString);
                    if (System.currentTimeMillis() - uploadTime > (1 * 60 * 1000)) { // 超过30分钟
                        System.out.println("删除的文件: " + key);
                        // 从OSS中删除文件
                        ossConfig.deleteObject(key);
                        // 从Redis中删除文件信息
                        redisTemplate.delete(key);
                    }
                }
            }
        }
    }
}
